﻿using B.S.Meeting.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.Meeting.Infrastructure.Implements
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        BaseDbContext db;

        public BaseRepository(BaseDbContext db)
        {
            this.db = db;
        }

        public async Task<int> AddAsync(T entity)
        {
            try
            {
                await db.Set<T>().AddAsync(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public IQueryable<T> GetAll()
        {
            try
            {
                return db.Set<T>().AsQueryable();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            try
            {
                return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<int> UpdAsync(T entity)
        {
            try
            {
                db.Set<T>().Update(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<int> Del(int id)
        {
            try
            {
                var list = db.Set<T>().Find(id);
                db.Set<T>().Remove(list);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> BatchDel(List<T> list)
        {
            try
            {
                db.Set<T>().UpdateRange(list);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
